package com.fingard.dsp.bank.directbank.bocom13;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.dsp.bank.directbank.bocom13.util.MD5;
import com.fingard.dsp.bank.directbank.bocom13.util.SeqNumUtil;
import com.fingard.dsp.bank.directbank.fngrd01.util.ExcelUtil;
import com.fingard.dsp.bank.directbank.spdb12.util.YBTSeqNumUtil;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.GZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.*;
import java.util.Date;
import java.util.HashMap;

public class BOCOM13ScheduleTask extends BOCOM13Base implements IScheduleTask {
	@Override
	public void execTask(TaskTimerSet timerSet) {
		try {
            if (timerSet.taskNameList.toLowerCase().contains("authorizedsubmit")) {
            	authorizationSubmit();
            }
            if (timerSet.taskNameList.toLowerCase().contains("authorizedquery")) {
            	authorizationQuery();
            }
			if (timerSet.taskNameList.toLowerCase().contains("pushsigndata")) {
				pushSignData();
			}
        } catch (Exception ex) {
            WriteBankLogLn(ex);
        }
	}
	
	/**
	 * 存量客户协议导入提交
	 * 
	 * @throws Exception 
	 */
	public void authorizationSubmit() throws Exception {
		FileInputStream fis = null;
		
		String authFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + "upload";
		File authFile = new File(authFilePath);
		WriteBankLogLn("开始读取本机目录:" + authFilePath);
		if (authFile.exists()) {
			File[] fileList = authFile.listFiles();
			for(File tmpFile : fileList) {
				if (tmpFile.getName().endsWith(".xlsx")) {
					WriteBankLogLn("当前待处理文件:" + tmpFile.getName());
					String[] tmpFileInfo = tmpFile.getName().replace(".xlsx", "").split("_");
					
					String accNum = tmpFileInfo[0];
					WriteBankLogLn("发起方账号:" + accNum);
					
					String reqBatchNo = tmpFileInfo[1];
					WriteBankLogLn("批号:" + reqBatchNo);
					
					String excelFileContent = ExcelUtil.read(tmpFile.getPath());
					WriteBankLogLn("当前待处理文件内容:\r\n" + excelFileContent);
					String totalNum = String.valueOf(excelFileContent.split("\r\n").length);
					
					String tmpPayDate = Format.Date8Format.format(new Date());
					
					String bankBranch = getBankConfig().getMapValueByKey("bankBranch", accNum);
					if (StringHelper.isNullOrEmpty(bankBranch)) {
						WriteBankLogLn("未配置账号[" + accNum + "]银行方分支机构映射,请检查config.xml中'bankBranch'配置项!");
						return;
					}

					String fileType = BOCOM13TransCode.batSign_ENDIIMPT;
					String tmpBatSeqNo = getBatSeqNo(getENDIIMPTDirectory(), 5);
					
					String tmpUploadFileName = "I_B_" + tmpPayDate + "_" + bankFront.corpNo + "_" + bankBranch + "_" + fileType + ".S." + tmpBatSeqNo;
					String tmpLocalFilePath = getTempFileDirectory() + File.separator + tmpUploadFileName;
					String tmpGZipFilePath = tmpLocalFilePath + ".gz";

					byte tmpByteSp = 0x0F;// 域分隔符
					byte tmpByteLn = (byte) '\n';// 换行符

					StringBuilder sbFileContent = new StringBuilder();

					sbFileContent.append("3012900");/* 银行方ID:(3012900:交通银行) */
					sbFileContent.append(tmpByteSp);

					sbFileContent.append(bankBranch);/* 银行分行代码:保险公司发起方账号开户分行代码 */
					sbFileContent.append(tmpByteSp);

					sbFileContent.append(tmpByteSp);/* 银行方业务日期 */
					sbFileContent.append(tmpByteSp);/* 银行方交易日期 */
					sbFileContent.append(tmpByteSp);/* 银行方交易时间 */
					sbFileContent.append(tmpByteSp);/* 银行方批次号 */

					sbFileContent.append(bankFront.corpNo);/*保险方ID: 保险公司编码 */
					sbFileContent.append(tmpByteSp);

					sbFileContent.append(tmpPayDate);/* 保险方业务日期(yyyyMMdd) */
					sbFileContent.append(tmpByteSp);

					sbFileContent.append(tmpPayDate);/* 保险方交易日期(yyyyMMdd) */
					sbFileContent.append(tmpByteSp);

					sbFileContent.append(Format.Time6Format.format(new Date()));/* 保险方交易时间 */
					sbFileContent.append(tmpByteSp);

					sbFileContent.append(reqBatchNo);/* 保险方批次号 */
					sbFileContent.append(tmpByteSp);

					sbFileContent.append(totalNum);/* 总笔数 */
					sbFileContent.append(tmpByteSp);

					sbFileContent.append(tmpByteSp);/* 成功笔数 */
					sbFileContent.append(tmpByteSp);/* 预留字段01 */
					sbFileContent.append(tmpByteSp);/* 预留字段02 */
					sbFileContent.append(tmpByteSp);/* 预留字段03 */
					sbFileContent.append(tmpByteSp);/* 预留字段04 */
					sbFileContent.append(tmpByteSp);/* 预留字段05 */
					sbFileContent.append(tmpByteSp);/* 预留字段06 */
					sbFileContent.append(tmpByteSp);/* 预留字段07 */
					sbFileContent.append(tmpByteSp);/* 预留字段08 */
					sbFileContent.append(tmpByteSp);/* 预留字段09 */
													/* 预留字段10 */

					int tmpRdCount = 0;
					String[] recordArray = excelFileContent.split("\r\n");
					for(String eachRecord : recordArray) {
						if (StringHelper.isNullOrEmpty(eachRecord)) {
							break;
						}
						// 每行明细:交易流水号0,投保单号1,保单号2,账号3,客户姓名4,证件类型5,证件号码6
						String[] bodyValues = eachRecord.split(",");
						tmpRdCount++;
						sbFileContent.append(tmpByteLn);

						sbFileContent.append(tmpRdCount);/* 记录序号 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append(tmpByteSp);/* 应答类型 */
						sbFileContent.append(tmpByteSp);/* 错误码 */
						sbFileContent.append(tmpByteSp);/* 错误说明 */
						sbFileContent.append(tmpByteSp);/* 银行方业务日期 */
						sbFileContent.append(tmpByteSp);/* 银行方流水号 */

						sbFileContent.append(tmpPayDate);/* 保险方业务日期 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append(bodyValues[0]);/* 保险方流水号 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append(bodyValues[1]);/* 投保单号 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append(bodyValues[2]);/* 保单号 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append(bodyValues[4]);/* 客户姓名 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append(convertCertTypeToBank(bodyValues[5]));/* 证件类型 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append(bodyValues[6]);/* 证件号码 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append(bodyValues[3]);/* 账号 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append("");/* 手机号码 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append("");/* 代收协议编号 */
						sbFileContent.append(tmpByteSp);

						sbFileContent.append(tmpByteSp);/* 预留字段01 */
						sbFileContent.append(tmpByteSp);/* 预留字段02 */
						sbFileContent.append(tmpByteSp);/* 预留字段03 */
						sbFileContent.append(tmpByteSp);/* 预留字段04 */
						sbFileContent.append(tmpByteSp);/* 预留字段05 */
						sbFileContent.append(tmpByteSp);/* 预留字段06 */
						sbFileContent.append(tmpByteSp);/* 预留字段07 */
						sbFileContent.append(tmpByteSp);/* 预留字段08 */
						sbFileContent.append(tmpByteSp);/* 预留字段09 */
														/* 预留字段10 */
					}

					WriteBankLogLn2("批量代收签约授权请求文件内容:\r\n" + sbFileContent.toString());
					WriteBankLogLn("待压缩批量代收签约授权请求文件保存本地路径:" + tmpLocalFilePath);
					FileHelper.writeFile(tmpLocalFilePath, sbFileContent.toString(), getCharset());

					GZipHelper.doCompressFile(tmpLocalFilePath, tmpGZipFilePath);
					WriteBankLogLn("压缩后批量代收签约授权请求文件保存本地路径：" + tmpGZipFilePath);

					// 2.文件传输
					// 2.1 报文1
					StringBuilder tmpSbPck1 = new StringBuilder();
					tmpSbPck1.append("I60901");/* 交易码 */
					tmpSbPck1.append("I");/* 文件创建方标识 */
					tmpSbPck1.append("B");/* 文件接收方标识 */
					tmpSbPck1.append(String.format("%-15s", bankFront.corpNo));/* 保险方ID */
					tmpSbPck1.append(String.format("%-10s", "3012900"));/* 银行方ID */
					tmpSbPck1.append(String.format("%-20s", bankBranch));/* 银行分行代码 */
					tmpSbPck1.append(tmpPayDate);/* 业务日期 */
					tmpSbPck1.append(String.format("%-20s", reqBatchNo));/* 交易流水号 */
					tmpSbPck1.append(tmpPayDate);/* 交易日期 */
					tmpSbPck1.append(Format.Time6Format.format(new Date()));/* 交易时间 */
					tmpSbPck1.append(String.format("%-128s", tmpUploadFileName + ".gz"));/* 压缩文件名称 */
					tmpSbPck1.append(String.format("%012d", new File(tmpGZipFilePath).length()));/* 文件大小 */
					int maxBlockSize = 2097152;
					int tmpBlockSize = (int) new File(tmpGZipFilePath).length();
					if (tmpBlockSize > maxBlockSize) {
						tmpBlockSize = maxBlockSize;
					}
					tmpSbPck1.append(String.format("%08d", tmpBlockSize));/* 数据包大小 */
					String tmpGZMD5 = MD5.generateFileMD5(tmpGZipFilePath);
					tmpSbPck1.append(String.format("%-200s", tmpGZMD5));/* 文件MD5校验值 */
					tmpSbPck1.append(String.format("%-1500s", ""));

					boolean tmpFinished = false;
					String tmpFileInfoCode = "";
					String tmpFileMsg = "";

					int tmpStep = 1;
					int tmpReadedLen = 0;
					byte[] tmpLastBuffer = new byte[0];
					int tmpLastBufLength = 0;
					byte[] tmpNowBuffer = new byte[0];
					int tmpNowBufLength = 0;
					int tmpLastSeq = -1;
					String tmpBankAskSeq = "";// 数据包序号

					String[] tmpBkRet = new String[] { "", "" };
					while (tmpReadedLen <= new File(tmpGZipFilePath).length()) {
						if (tmpStep == 1) {
							WriteBankLogLn("发送银行的【报文1】请求数据:\r\n" + tmpSbPck1);
							tmpBkRet = sendToBank(tmpSbPck1.toString(), bankFront.filePort);
							tmpStep++;
						} else {
							byte[] bytesBody3 = ("I60902" + tmpBankAskSeq).getBytes(getCharset());
							WriteBankLogLn("发送银行的报文3请求数据，不包含数据包为:" + "I60902" + tmpBankAskSeq);
							byte[] bytesP3ToSend = new byte[bytesBody3.length + tmpNowBufLength];
							System.arraycopy(bytesBody3, 0, bytesP3ToSend, 0, bytesBody3.length);
							System.arraycopy(tmpNowBuffer, 0, bytesP3ToSend, bytesBody3.length, tmpNowBufLength);
							tmpBkRet = sendToBank(new String(bytesP3ToSend), bankFront.filePort);
							tmpLastBuffer = tmpNowBuffer;
							tmpLastBufLength = tmpNowBufLength;
							tmpLastSeq = Integer.parseInt(tmpBankAskSeq);
						}
						tmpBankAskSeq = "";
						tmpNowBuffer = new byte[0];
						tmpNowBufLength = 0;

						if (tmpBkRet[0].length() == 0) {
							byte[] bytesBkRet = tmpBkRet[1].getBytes(getCharset());
							if (bytesBkRet.length > 24) {
								tmpBankAskSeq = new String(bytesBkRet, 25, 6);
								byte tmpRespType = bytesBkRet[24];
								if (tmpRespType == 'G') {
									WriteBankLogLn("【报文2】响应数据中数据包序号：" + tmpBankAskSeq);
									int tmpAskSeq = Integer.parseInt(tmpBankAskSeq);
									int expectedSeq = tmpLastSeq + 1;
									if (tmpAskSeq == expectedSeq) {// 继续读取文件
										tmpNowBuffer = new byte[maxBlockSize];
										
										fis = new FileInputStream(new File(tmpGZipFilePath));
										byte[] bytes = new byte[maxBlockSize];
										fis.read(bytes);
										tmpNowBufLength = bytes.length;
										if (tmpNowBufLength > 0) {
											tmpReadedLen += tmpNowBufLength;
										} else {
											tmpFinished = false;
											tmpFileMsg = "数据包序号" + tmpAskSeq + "已无数据可读";
											break;
										}
									} else {
										tmpFinished = false;
										tmpFileMsg = "数据包序号" + tmpAskSeq + "与预期序号" + expectedSeq + "不符";
										break;
									}
								} else if (tmpRespType == 'R') {
									WriteBankLogLn("3.【报文2】请求重传数据包序号：" + tmpBankAskSeq);
									int tmpReSendSeq = Integer.parseInt(tmpBankAskSeq);
									if (tmpReSendSeq == tmpLastSeq) {// 继续读取文件
										tmpNowBuffer = tmpLastBuffer;
										tmpNowBufLength = tmpLastBufLength;
									} else {
										tmpFinished = false;
										tmpFileMsg = "重传数据包序号" + tmpReSendSeq + "与上次序号" + tmpLastSeq + "不符";
										break;
									}
								} else if (tmpRespType == 'N') {
									WriteBankLogLn("3.【报文4】N-文件传输成功：" + tmpBankAskSeq);
									tmpFinished = true;
									break;
								} else if (tmpRespType == 'E') {
									WriteBankLogLn("3.【报文5】E-文件传输失败：" + tmpBankAskSeq);
									tmpFinished = false;
									tmpFileInfoCode = tmpBankAskSeq;
									tmpFileMsg = new String(bytesBkRet, 31, 300).trim();
									break;
								} else if (tmpRespType == 'A') {
									WriteBankLogLn("【报文5】A-文件传输异常：" + tmpBankAskSeq);
									tmpFinished = false;
									tmpFileInfoCode = tmpBankAskSeq;
									tmpFileMsg = new String(bytesBkRet, 31, 300).trim();
									break;
								} else {
									WriteBankLogLn("3.【报文2】不能识别的应答类型：" + (char) bytesBkRet[24]);
									tmpFinished = false;
									tmpFileMsg = "不能识别的应答类型：" + (char) bytesBkRet[24];
									break;
								}
							}
						} else {
							tmpFinished = false;
							tmpFileInfoCode = "E9999";
							tmpFileMsg = tmpBkRet[1];
							break;
						}
					}
					
					if (tmpFinished) {
						// 发起文件确认(B60911/I60911)
						WriteBankLogLn("2.文件发送成功，进行文件确认，连接服务：" + bankFront.serverIP + ":" + bankFront.serverPort);
						
						BOCOM13Header tmpBankHeader = new BOCOM13Header();
						tmpBankHeader.transCode = "I60911";
						tmpBankHeader.reqSeqID = reqBatchNo;
						
						XmlTextWriter xmlWriter = new XmlTextWriter();
						writeCommonHeader(xmlWriter, tmpBankHeader);

						xmlWriter.writeStartElement("Body");
						xmlWriter.writeElementString("FileName", tmpUploadFileName + ".gz");/* 压缩文件名称 */
						xmlWriter.writeElementString("TotalNum", totalNum);/* 总笔数 */
						xmlWriter.writeElementString("TotalAmt", "");/* 总金额 */
						xmlWriter.writeElementString("BatNo", reqBatchNo);/* 创建方批次号 */
						xmlWriter.writeEndDocument();

						String[] tmpRetStr = sendToBank(xmlWriter.toXmlString(), bankFront.serverPort);
						
						if (tmpRetStr[0].length() == 0) {
							StringBuilder tmpSbMsg = new StringBuilder();
							XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
							if (tmpBkReader != null) {
								String tmpMsgType = tmpBkReader.getFirstText("/Rsp/Head/MsgType");
								String tmpErrCode = tmpBkReader.getFirstText("/Rsp/Head/ErrCode");
								if ("N".equals(tmpMsgType) && "000000".equals(tmpErrCode)) {
									WriteBankLogLn("协议导入发送成功!");
								} else {
									WriteBankLogLn("协议导入发送失败:" + tmpBkReader.getFirstText("/Rsp/Head/ErrMsg"));
								}
							} else {
								WriteBankLogLn(tmpSbMsg.toString());
							}
						} else {
							WriteBankLogLn(tmpRetStr[1]);
						}
					} else {
						WriteBankLogLn(tmpFileInfoCode + "+" + tmpFileMsg);
					}
				}
			}
		} else {
			WriteBankLogLn("本机协议导入目录:[" + authFilePath + "]不存在，暂不进行协议导入操作!");
		}
		
		if (fis != null) {
			fis.close();
		}
		return;
	}
	
	/**
	 * 存量客户协议导入结果查询
	 * 
	 * @throws Exception 
	 */
	public void authorizationQuery() throws Exception {
		FileOutputStream fos = null;
		
		File authFile = new File(bankFront.bkTransFolder);
		WriteBankLogLn("开始读取本机目录:" + bankFront.bkTransFolder);
		if (authFile.exists()) {
			File[] fileList = authFile.listFiles();
			for(File tmpFile : fileList) {
				if (tmpFile.getName().endsWith(".xlsx")) {
					WriteBankLogLn("当前待查询处理文件:" + tmpFile.getName());
					String reqSeqID = tmpFile.getName().replace(".xlsx", "");
					if(reqSeqID.contains("_")){
						reqSeqID = reqSeqID.split("_")[1];
					}
					WriteBankLogLn("待查询批次号:" + reqSeqID);
					
					String tmpNotifyDataPath = getNotifyDataDirectory() + File.separator + reqSeqID + ".txt";
					WriteBankLogLn("银行结果文件路径:" + tmpNotifyDataPath);
					
					if (new File(tmpNotifyDataPath).exists()) {
						String tmpStrRet = FileHelper.readFileText(tmpNotifyDataPath, getCharset());
						WriteBankLogLn("银行结果文件内容:\r\n" + tmpStrRet);
						StringReader strReader = new StringReader(tmpStrRet);
						BufferedReader tmpReader = new BufferedReader(strReader);
						String[] line1 = tmpReader.readLine().split(",");
						if (line1.length > 10) {
							String tmpBkBatNO = line1[10];
							if (reqSeqID.equals(tmpBkBatNO)) {
								// 往本地excel写入结果文件
								
								//第一步，创建一个workbook对应一个excel文件
						        HSSFWorkbook workbook = new HSSFWorkbook();
						        //第二部，在workbook中创建一个sheet对应excel中的sheet
						        HSSFSheet sheet = workbook.createSheet("Sheet1");
						        //第三部，在sheet表中添加表头第0行，老版本的poi对sheet的行列有限制
						        HSSFRow row = sheet.createRow(0);
						        //第四步，创建单元格，设置表头
						        HSSFCell cell = row.createCell(0);
						        cell.setCellValue("交易流水号");
						        cell = row.createCell(1);
						        cell.setCellValue("签约状态");
						        cell = row.createCell(2);
						        cell.setCellValue("协议编号");
						        cell = row.createCell(3);
						        cell.setCellValue("失败原因");
						        
						        //第五步，写入数据
						        int i = 0;
						        while(true) {
									String[] eachLine = tmpReader.readLine().split(",");
									if (eachLine.length > 16) {
										HSSFRow row1 = sheet.createRow(i + 1);
										
										row1.createCell(0).setCellValue(eachLine[7]);
										
										String tmpBkDtState = eachLine[1];
			                            String tmpBkDtInfoCode = eachLine[2];
			                            String tmpBkDtInfo = eachLine[3];
			                            if ("N".equals(tmpBkDtState) && "000000".equals(tmpBkDtInfoCode)) {
			                            	row1.createCell(1).setCellValue("2");
			                            } else {
			                            	row1.createCell(1).setCellValue("3");
			                            }
			                            row1.createCell(2).setCellValue(eachLine[15]);
			                            row1.createCell(3).setCellValue(tmpBkDtInfo);
										i++;
									} else {
										break;
									}
						        }
						        
						        //将文件保存到指定的位置
						        String resultExcelFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + "down" + File.separator + tmpFile.getName(); 
					            WriteBankLogLn("存量客户签约结果保存本机路径:" + resultExcelFilePath);
					        	fos = new FileOutputStream(resultExcelFilePath);
					            workbook.write(fos);
					            WriteBankLogLn("存量客户签约结果保存成功!");
					            fos.close();
							} else {
								WriteBankLogLn("结果文件中的批次号" + tmpBkBatNO + "与请求批次号" + reqSeqID + "不一致");
							}
						} else {
							WriteBankLogLn("结果文件格式不符合预期，首行字段数不足16个");
						}
					} else {
						WriteBankLogLn("当前未收到交行的结果文件");
					}
				}
			}
		} else {
			WriteBankLogLn("本机协议导入目录:[" + bankFront.bkTransFolder + "]不存在，暂无法查询结果!");
		}
		if (fos != null) {
			fos.close();
		}
	}

	public void pushSignData() throws Exception {
		String notifyDirectory = getNotifyDirectory();
		File authFile = new File(notifyDirectory);
		WriteBankLogLn("开始读取本机目录:" + notifyDirectory);
		if (authFile.exists()) {
			JSONObject signNotifyJson = new JSONObject();
			signNotifyJson.put("TransSource","ATS");
			signNotifyJson.put("TransCode","630SignSyncData");
			signNotifyJson.put("TransSeq",Format.DateTime14Format.format(new Date()));
			signNotifyJson.put("TransType","Signed");

			JSONArray inJsonArray = new JSONArray();

			File[] fileList = authFile.listFiles();
			for(File tmpNotifyFile : fileList) {
			    WriteBankLogLn("当前文件名:" + tmpNotifyFile.getName());
			    if (tmpNotifyFile.getName().startsWith("qry_authInfo")) {
                    WriteBankLogLn("开始解析当前银保通代销保单签约结果文件:" + tmpNotifyFile.getAbsolutePath());
                    String tmpStrRet = FileHelper.readToString(tmpNotifyFile, getCharset());
                    WriteBankLogLn("当前银保通代销保单签约结果文件内容:\r\n" + tmpStrRet);

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    tmpReader.readLine();

                    while(true) {
                        String tmpLine = tmpReader.readLine();
                        if (tmpLine == null) {
                            break;
                        }
                        if (inJsonArray.size() >= 500) {
                            break;
                        }

                        String[] eachLine = tmpLine.split("\u000F");

                        JSONObject detailJson = new JSONObject();
                        if (eachLine.length > 7) {
                            detailJson.put("RdSeq",eachLine[7]);
                        }
                        detailJson.put("CorpEntity",bankFront.corporation);
                        detailJson.put("PrivateFlag","1");
                        detailJson.put("BatchFlag","0");
                        detailJson.put("OppBank","");
                        if (eachLine.length > 13) {
                            detailJson.put("OppAct",eachLine[13]);
                        }
                        if (eachLine.length > 10) {
                            detailJson.put("OppActName",eachLine[10]);
                        }
                        if (eachLine.length > 14) {
                            detailJson.put("SignNo",eachLine[14]);
                        }
                        if (eachLine.length > 11) {
                            detailJson.put("CertType",convertCertTypeToBank(eachLine[11]));
                        }
                        detailJson.put("CellPhone","");
                        if (eachLine.length > 12) {
                            detailJson.put("CertNumber",eachLine[12]);
                        }
                        detailJson.put("CardType","2");
                        detailJson.put("CVV2","");
                        detailJson.put("ExpiredDate","");
                        detailJson.put("LGL_Name","");
                        detailJson.put("LGL_CertType","");
                        detailJson.put("LGL_CertNumber","");
                        if (eachLine.length > 8) {
                            detailJson.put("SourceNoteCode",eachLine[8]);
                        }
                        if (eachLine.length > 9) {
                            detailJson.put("PolicyNo",eachLine[9]);
                        }
                        detailJson.put("DisableDate","");
                        detailJson.put("SingleLimit","");
                        detailJson.put("LimitPeriodUnit","");
                        detailJson.put("MaxCountLimit","");
                        detailJson.put("NoteMoney","");
                        detailJson.put("InsureID","");
                        detailJson.put("InsureName","");

                        // 插入db表，并设置推送状态为未推送
                        HashMap<String, String> mapSeqNum = SeqNumUtil.getSendDate(eachLine[7]);
                        if (mapSeqNum.isEmpty()) {
                            // 未发生签约申请
                            // 插入新记录，推送状态为未推送
                            StringBuilder sbLog = new StringBuilder();
                            boolean saved = SeqNumUtil.saveSendDate(detailJson, sbLog);
                            if(!saved){
                                throw new Exception(sbLog.toString());
                            }
                            inJsonArray.add(detailJson);
                        } else {
                            // 判断推送状态，如果未推送才继续推送，否则过滤
                            String pushStatus = mapSeqNum.get("pushstatus");
                            if (pushStatus != null && "0".equalsIgnoreCase(pushStatus)) {
                                StringBuilder sbLog = new StringBuilder();
                                boolean saved = SeqNumUtil.saveSendDate(detailJson, sbLog);
                                if(!saved){
                                    throw new Exception(sbLog.toString());
                                }
                                inJsonArray.add(detailJson);
                            }
                        }
                    }
                } else {
			        WriteBankLogLn("当前文件名非银保通代销保单签约结果文件，不处理.");
                }
			}

			signNotifyJson.put("IN", inJsonArray);

			if (inJsonArray.size() > 0) {
				String tmpStrSend = JSON.toJSONString(signNotifyJson);
				String[] tmpStrRet = sendToBank(tmpStrSend);
				if (tmpStrRet[0].length() == 0) {
					if (tmpStrRet[1].contains("{")) {
						JSONObject respJson = JSONObject.parseObject(tmpStrRet[1]);
						JSONArray jsonArray = respJson.getJSONArray("OUT");
						if (jsonArray.size() > 0) {
							for (int i =0; i< jsonArray.size();i++) {
								JSONObject respJsonDetail = (JSONObject) jsonArray.get(i);

								String asknumber = (String) respJsonDetail.get("RdSeq");
								String respCode = (String) respJsonDetail.get("RdCode");
								if ("success".equalsIgnoreCase(respCode)) {
									// 更新db表推送状态为已推送
									StringBuilder sbLog = new StringBuilder();
									boolean saved = SeqNumUtil.updateSendDate(asknumber, sbLog);
									if(!saved){
										throw new Exception(sbLog.toString());
									}
								}
							}
						} else {
							WriteBankLogLn("推送失败,渠道返回内容没有detail...,不返回原因:" + respJson.getString("RdMsg"));
						}
					} else {
						WriteBankLogLn("推送响应格式非法:" + tmpStrRet[1]);
					}
				} else {
					WriteBankLogLn("推送失败:" + tmpStrRet[1]);
				}
			} else {
				WriteBankLogLn("本机银保通代销保单签约结果文件暂无需要推送的签约用户信息,暂不推送!");
			}
		} else {
			WriteBankLogLn("本机银保通代销保单签约结果文件目录:[" + notifyDirectory + "]不存在，暂不推送!");
		}
	}
}